package xx.pro.shiro.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import xx.pro.shiro.common.Result;
import xx.pro.shiro.entity.SysPermissions;
import xx.pro.shiro.enums.ResultCodeEnum;

@RestController
public class LoginController {


    @GetMapping("/login")
    public Result login(String userName, String passWord) {
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(passWord)) {
            return Result.fail(ResultCodeEnum.USER_OR_PWD_NOT_EMPTY);
        }
        //用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userName, passWord);
        try {
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
            return Result.fail(ResultCodeEnum.USER_NOT_EXISTS);
        } catch (AuthenticationException e) {
            return Result.fail(ResultCodeEnum.USER_ERROR);
        } catch (AuthorizationException e) {
            return Result.fail(ResultCodeEnum.AUTHORITY_UNAUTHORIZED);
        }
        return Result.success("登录成功");
    }


    @GetMapping("delete")
    public Result delete() {
        Subject subject = SecurityUtils.getSubject();
        if(subject.isPermitted("user:delete")){
            return Result.success("delete success");
        }else{
            return Result.fail(ResultCodeEnum.AUTHORITY_UNAUTHORIZED);
        }
    }


    @RequiresPermissions("user:update")
    @GetMapping("update")
    public Result<String> update() {
        return Result.success("update success");
    }


    @RequiresPermissions("user:add")
    @GetMapping("add")
    public Result<String> add() {
        return Result.success("add success ");
    }

}
